package com.kamloo.stg.data.db;

import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class StopDAO {
	private SQLiteDatabase m_database;
	private MySQLiteHelper m_dbHelper;
	public static final String TABLE_NAME 		 = "stop";
	public static final String COLUMN_ID 		 = "_id";
	public static final String COLUMN_NAME 		 = "name";
	public static final String COLUMN_LATITUDE 	 = "latitude";
	public static final String COLUMN_LONGITUDE	 = "longitude";
	private String[] m_allColumns = { COLUMN_ID, COLUMN_NAME, COLUMN_LATITUDE, COLUMN_LONGITUDE };
	
	public static final String TABLE_CREATE = 
			"CREATE TABLE " + 
		    TABLE_NAME + "(" + 
		    COLUMN_ID + " INTEGER PRIMARY KEY, " +  
		    COLUMN_NAME	+ " TEXT NOT NULL, " + 
		    COLUMN_LATITUDE + " REAL, " + 
		    COLUMN_LONGITUDE + " REAL);";
	
	public StopDAO(Context context) {
		m_dbHelper = new MySQLiteHelper(context);
	}

	public void open() throws SQLException {
		m_database = m_dbHelper.getWritableDatabase();
	}

	public void close() {
		m_dbHelper.close();
	}

	
	public void add(Stop stop) {
		ContentValues values = new ContentValues();
		values.put(COLUMN_ID, stop.getId());
		values.put(COLUMN_NAME, stop.getName());
		values.put(COLUMN_LATITUDE, stop.getLatitude());
		values.put(COLUMN_LONGITUDE, stop.getLongitude());
		m_database.insert(TABLE_NAME, null, values);
	}
	
	public void delete(int id) {
		System.out.println("Stop deleted with id: " + id);
		m_database.delete(TABLE_NAME, COLUMN_ID + " = " + id, null);
	}
	
	public Stop select(int id) {
		Cursor cur = m_database.query(TABLE_NAME, m_allColumns, COLUMN_ID + " = " + id, 
									  null, null, null, null);
		
		if (cur != null)
			cur.moveToFirst();
		
		Stop newStop = cursorToStop(cur);
		cur.close();
		return newStop;
	}
	
	public ArrayList<Stop> selectAll(){
		ArrayList<Stop> stops = new ArrayList<Stop>();
		
		Cursor cur = m_database.query(TABLE_NAME, m_allColumns, 
				  					  null, null, null, null, null);

		if (cur != null) {
			cur.moveToFirst();
			while (!cur.isAfterLast()) {
				stops.add(cursorToStop(cur));
				cur.moveToNext();
			}
		}

		cur.close();
		return stops;
	}
	
	public void update(Stop stop) {
		ContentValues values = new ContentValues();
		values.put(COLUMN_NAME, stop.getName());
		values.put(COLUMN_LATITUDE, stop.getLatitude());
		values.put(COLUMN_LONGITUDE, stop.getLongitude());
		m_database.update(TABLE_NAME, values, COLUMN_ID + " = " + stop.getId(), null);
	}	
	
	private Stop cursorToStop(Cursor cursor) {
		return new Stop(cursor.getInt(0),
						cursor.getString(1),
						cursor.getDouble(2),
						cursor.getDouble(3));
	}
}
